﻿using System;
using System.Runtime.InteropServices;
using LabChecker.Client.CheckServiceReference;
using LabChecker.Models.Programs;
using LabChecker.ViewModels;
using Microsoft.Win32;

namespace LabChecker.Client
{
    [ComVisible(true)]
    public class CheckHelper
    {
        public event EventHandler<CheckCompletedEventArgs> CheckCompleted;
        public event EventHandler CheckStarted;

        public void Check(int taskId, string sLanguage)
        {
            var dlg = new OpenFileDialog();
            dlg.Filter = "Code file|*." + sLanguage;

            if (dlg.ShowDialog() != true)
            {
                return;
            }

            var programCode = System.IO.File.ReadAllText(dlg.FileName);

            if (CheckStarted != null)
            {
                CheckStarted(this, EventArgs.Empty);
            }

            var checkService = new CheckServiceClient();

            checkService.GetTaskCompleted += (s, a) =>
            {
                var task = a.Result;

                Models.CheckResults.TaskBase checkResult;

                using (var program = CreateProgram(sLanguage, programCode))
                {
                    checkResult = task.Check(program);
                }

                var checkResultViewModel = new CheckResultViewModel(checkResult);

                if (CheckCompleted != null)
                {
                    CheckCompleted(this, new CheckCompletedEventArgs(checkResultViewModel));
                }
            };

            checkService.GetTaskAsync(taskId);
        }

        private static Program CreateProgram(string language, string programCode)
        {            
            switch (language)
            {
                case "cs":
                    return new CSharpProgram(programCode);
                case "cpp":
                    return new CppProgram(programCode);
                default:
                    throw new ArgumentException("Unknown language");                    
            }            
        }
    }
}
